package org.example.controller;

import org.example.internalCommon.dto.ResponseResult;
import org.example.internalCommon.response.NumberCodeResponse;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import java.util.Random;

@RestController
public class NumberCodeController {


    @GetMapping("/numberCode/{size}")
    public ResponseResult numberCode(@PathVariable("size") int size){
        System.out.println(size);
        NumberCodeResponse numberCodeResponse = new NumberCodeResponse();
        numberCodeResponse.setNumberCode(String.valueOf(generateRandomNumber(size)));
        return ResponseResult.success(numberCodeResponse);
    }

    public int generateRandomNumber(int digitCount) {
        if (digitCount <= 0) {
            throw new IllegalArgumentException("数字位数必须大于0");
        }

        Random random = new Random();

        // 首位数字生成，范围是 1-9
        int firstDigit = random.nextInt(9) + 1;

        // 如果只有一位数，直接返回首位
        if (digitCount == 1) {
            return firstDigit;
        }

        // 剩余位数的生成，范围是 0 到 (10^(digitCount - 1) - 1)
        int remainingDigits = (int) Math.pow(10, digitCount - 1);
        int lowerBound = (int) Math.pow(10, digitCount - 2);
        int remainingPart = random.nextInt(remainingDigits - lowerBound) + lowerBound;

        // 拼接首位和剩余部分
        return Integer.parseInt(firstDigit + String.valueOf(remainingPart));
    }

}
